﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using QuickOpen.Framework;

namespace QuickOpen.Controls
{
    public class FilterTextBox : TextBox
    {
        public FilterTextBox() { }

        /// <summary>
        /// Don't fire OnTextChanged if flagged for text change without event.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnTextChanged(EventArgs e)
        {
            try
            {
                if (!_changingText)
                {
                    _changingText = true;
                    base.OnTextChanged(e);
                }
            }
            finally
            {
                _changingText = false;
            }
        }

        public void Backspace()
        {
            if (Text.Length > 0 && SelectedText.Length > 0)
            {
                _changingText = true;
                try
                {
                    Text = this.Text.Substring(0, SelectionStart);
                    Select(Text.Length, 0);
                }
                finally
                {
                    _changingText = false;
                }
            }
        }

        public void AutoComplete(IFilterableItem iFilterableItem)
        {
            try
            {
                _changingText = true;
                if (Text.Length == 0 || !iFilterableItem.ShortName.StartsWith(Text, StringComparison.CurrentCultureIgnoreCase))
                    return;

                int additionIndex = Text.Length;
                Text = Text + iFilterableItem.ShortName.Substring(additionIndex);
                Select(additionIndex, Text.Length - additionIndex);
            }
            finally
            {
                _changingText = false;
            }
        }

        private bool _changingText;
    }
}
